package com.mysoft.gfyx.marketdevelop.service.impl;

import com.google.common.base.Joiner;
import com.mysoft.framework.common.exception.BusinessLogicException;
import com.mysoft.framework.modeling.dto.*;
import com.mysoft.framework.service.AppService;
import com.mysoft.gfyx.common.dto.ListResult;
import com.mysoft.gfyx.common.rpc.bigdata.BigDataClientFactoryService;
import com.mysoft.gfyx.common.rpc.bigdata.BigDataClientService;
import com.mysoft.gfyx.common.rpc.bigdata.dto.BigdataBaseResponseDto;
import com.mysoft.gfyx.common.rpc.bigdata.dto.GetSupplierListRequestDto;
import com.mysoft.gfyx.common.rpc.mpapi.MpapiClientFactoryService;
import com.mysoft.gfyx.common.rpc.mpapi.MpapiClientService;
import com.mysoft.gfyx.common.rpc.mpapi.dto.CheckYcgMemberRequestDto;
import com.mysoft.gfyx.common.rpc.mpapi.dto.CheckYcgMemberResponseDto;
import com.mysoft.gfyx.common.ycg.YcgFileService;
import com.mysoft.gfyx.marketdevelop.dao.entity.OpTelViewHistory;
import com.mysoft.gfyx.marketdevelop.mip.GetSupplierDataService;
import com.mysoft.gfyx.marketdevelop.mip.dto.CheckSupplierMainDataResponseDto;
import com.mysoft.gfyx.marketdevelop.mip.dto.SupplierListRequestDto;
import com.mysoft.gfyx.marketdevelop.mip.dto.TjCustom.GetSupplierContactRequestDto;
import com.mysoft.gfyx.marketdevelop.mip.dto.TjCustom.GetSupplierDetailTableRequestDto;
import com.mysoft.gfyx.marketdevelop.mip.dto.TjCustom.SqlApiResponseDto;
import com.mysoft.gfyx.marketdevelop.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

@Service
public class SupplierServiceImp extends AppService implements SupplierService {

    @Autowired
    GetSupplierDataService getSupplierDataService;

    @Autowired
    SupplierService supplierService;

    @Autowired
    LabelService labelService;

    @Autowired
    private YcgFileService ycgFileService;

    @Resource
    private ProvinceRadarService provinceRadarService;
    @Autowired
    private MpapiClientFactoryService mpapiClientFactoryService;

    @Autowired
    private BigDataClientFactoryService bigDataClientFactoryService;

    @Autowired
    private CommonService commonService;

    public FieldsSetting loadFields() {
        //硬编码的获取字段逻辑
        FieldsSetting fieldsSetting = new FieldsSetting();
        fieldsSetting.setIdField("id");
        fieldsSetting.setFields(new ArrayList<>());
        String groupName = "supplier";
        fieldsSetting.getFields().add(new DataApiField("id", groupName, "主键id", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("supplier_id", groupName, "供应商ID", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("supplier_name", groupName, "供应商名称", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("organizing_code", groupName, "建设单位信用代码", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("supplier_logo", groupName, "建设单位logo", FieldType.Picture));
        fieldsSetting.getFields().add(new DataApiField("legal_name", groupName, "企业法人", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("regist_capi", groupName, "注册资金", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("establish_date", groupName, "成立时间", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("term_start", groupName, "营业开始时间", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("term_end", groupName, "营业结束时间", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("status", groupName, "经营状态", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("enterprise_nature", groupName, "企业类型", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("scope", groupName, "经营范围", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("category", groupName, "服务分类", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province", groupName, "区域（省）", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province_code", groupName, "区域（省）Code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("city", groupName, "区域（市）", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("city_code", groupName, "区域（市）Code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("address", groupName, "企业地址", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("number_of_employees", groupName, "公司规模", FieldType.Decimal));
        fieldsSetting.getFields().add(new DataApiField("company_profile", groupName, "公司简介", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("coop_cnt", groupName, "总合作项目", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("contact_cnt", groupName, "联系人数", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("coop_amt", groupName, "总合作金额", FieldType.String));

        // 返回
        return fieldsSetting;
    }

    public ListDataResult loadData(LoadDataParams options) {
        SupplierListRequestDto dto = new SupplierListRequestDto();
        dto.setPageNum(options.getPageIndex() + 1);
        dto.setPageSize(options.getPageSize());
        dto.setProvince_code(options.getOptions().getContext().get("province_code").toString());
        dto.addFilterByLoadDataApi(options.getOptions().getFilters());

        if (dto.getProvince_code() != null && dto.getProvince_code().equals("0")) {
            dto.setProvince_code("");//如果是0,表示全国，则设置为空
        }
        SqlApiResponseDto res = getSupplierDataService.getSupplier(dto);
        if (res.getData() == null || res.getData().getRows().size() == 0) {
            ListDataResult result = new ListDataResult();
            result.setTotal(0);
            result.setData(new ArrayList<>());
            return result;
        }

        ListResult<Map<String, Object>> listDataResult = new ListResult<>();
        listDataResult.setTotal(res.getData().getTotalNum());
        res.getData().getRows().forEach(p -> {
            this.processSupplier(p);
        });
        ArrayList arrayList = new ArrayList();
        arrayList.addAll(res.getData().getRows());
        supplierService.processSupplierTag(arrayList);
        listDataResult.setData(res.getData().getRows());
        //处理返回数据结构
        ListDataResult result = new ListDataResult();
        result.setTotal(listDataResult.getTotal());
        result.setData(listDataResult.getData());
        return result;
    }

    /**
     * 处理供应商数据格式
     *
     * @param
     * @param
     * @return
     */
    public Map<String, Object> processSupplier(Map<String, Object> p) {
        if (p.get("term_start") != null && !p.get("term_start").equals(""))
            p.put("term_start", p.get("term_start").toString().substring(0, 10));

        if (p.get("term_end") != null && !p.get("term_end").equals(""))
            p.put("term_end", p.get("term_end").toString().substring(0, 10));

        if (p.get("province") != null && p.get("city") != null) {
            String provinceName = p.get("province").equals(p.get("city")) ? "" : p.get("province").toString();
            String cityName = p.get("city") == null ? "" : p.get("city").toString();
            p.put("province_and_city", provinceName + cityName);
        }
        if (p.get("supplier_id") != null && p.get("supplier_logo") != null) {
            p.put("supplier_logo", ycgFileService.getEnterpriseLogo(p.get("supplier_id").toString(), p.get("supplier_logo").toString()));
        }
        return p;
    }


    public void processSupplierTag(ArrayList<Map<String, Object>> list) {
        ArrayList<String> tagList = new ArrayList<>();
        list.forEach(p -> {
            if (p.get("organizing_code") != null && !p.get("organizing_code").equals("")) {
                tagList.add(p.get("organizing_code").toString());
            }
        });
        //标签
        if (tagList.size() > 0) {
            GetSupplierDetailTableRequestDto getSupplierDetailTableRequestDto = new GetSupplierDetailTableRequestDto();
            getSupplierDetailTableRequestDto.setPageSize(10000);
            getSupplierDetailTableRequestDto.setOrganizing_code_list(Joiner.on(",").join(tagList));
            SqlApiResponseDto allTag = getSupplierDataService.getSupplierTag(getSupplierDetailTableRequestDto);

            //处理标签
            list.forEach(m -> {
                ArrayList<String> rawTagList = new ArrayList<>();
                allTag.getData().getRows().forEach(n -> {
                    if (m.get("organizing_code").equals(n.get("organizing_code"))) {
                        if (n.get("ycg_com_label") != null && !n.get("ycg_com_label").equals("")) {
                            rawTagList.add(n.get("ycg_com_label").toString());
                        }
                        if (n.get("deep_ploughing_area_label") != null && !n.get("deep_ploughing_area_label").equals("")) {
                            rawTagList.add(n.get("deep_ploughing_area_label").toString());
                        }

                    }
                });
                String tagStr = Joiner.on(",").join(rawTagList);
                m.put("tags", tagStr);
            });

        }
    }

    public void FilterProvince(List<Filter> filters) {
        if (filters.size() > 0) {
            for (int i = 0; i < filters.size(); i++) {
                if (filters.get(i).getCondition().size() > 0 && filters.get(i).getCondition().get(0).getField().equals("province_code") && filters.get(i).getCondition().get(0).getValue().equals("0")) {
                    filters.remove(i);
                }
            }
        }
    }

    public Map<String, Object> getSupplierMainData(String organizingCode) {
        if (organizingCode.isEmpty()) {
            throw new BusinessLogicException("公司的信用代码不能为空" + organizingCode);
        }
        SupplierListRequestDto dto = new SupplierListRequestDto();
        dto.setPageNum(1);
        dto.setPageSize(10);
        dto.setOrganizing_code(organizingCode);
        SqlApiResponseDto res = getSupplierDataService.getSupplier(dto);
        if (res.getData() == null || res.getData().getRows().size() == 0) {
            throw new BusinessLogicException("未找到相关供应商数据：" + organizingCode);
        }
        ArrayList arrayList = new ArrayList();
        arrayList.addAll(res.getData().getRows());
        supplierService.processSupplierTag(arrayList);
        Map<String, Object> result = new HashMap<>();
        AtomicReference<Map<String, Object>> finalResult = new AtomicReference<>(result);
        res.getData().getRows().forEach(p -> {
            this.processSupplier(p);
            if (p.get("tags").toString().contains("钻石供应商")) {
                p.put("is_diamond", 1);//钻石供应商
            } else {
                p.put("is_diamond", 0);
            }
            p.put("tags", labelService.loadLabelFromCommaString(p.get("tags").toString()));//详情页标签需要特别处理
            finalResult.set(p);

            //数据状态
            if (p.get("organizing_code") != null) {
                p.put("oppty_status", commonService.getOpptyStatus(CommonService.BigDataType.SUPPLIER.toString(), p.get("organizing_code").toString(), true));
            }
        });
        return finalResult.get();
    }

    @Override
    public List<CheckSupplierMainDataResponseDto> getSupplierMainDataMultiName(List<String> supplierNameList) {
        if (supplierNameList.size() == 0) {
            return new ArrayList<>();
        }
        // 最大允许10个
        List<String> subSupplierNameList = supplierNameList.subList(0, Math.min(10, supplierNameList.size()));

        BigDataClientService bigDataClientService = bigDataClientFactoryService.getBigDataClientService();
        GetSupplierListRequestDto getSupplierListRequestDto = new GetSupplierListRequestDto();
        getSupplierListRequestDto.setSupplier_name(String.join(",", subSupplierNameList));
        BigdataBaseResponseDto res = bigDataClientService.getSupplierList(getSupplierListRequestDto);
        if (res.getErrCode() != 0) {
            throw new BusinessLogicException("获取供应商列表报错 " + res.getErrMsg());
        }
//        if (res.getData() == null || res.getData().getRows().size() == 0) {
//            new ArrayList<>();
//        }
        List<CheckSupplierMainDataResponseDto> checkSupplierMainDataResponseDtoList = new ArrayList<>();
        subSupplierNameList.forEach(supplierName -> {
            CheckSupplierMainDataResponseDto checkSupplierMainDataResponseDto = new CheckSupplierMainDataResponseDto();
            checkSupplierMainDataResponseDto.setSupplierName(supplierName);
            checkSupplierMainDataResponseDto.setIsInMainData(0);
            res.getData().getRows().forEach(row -> {
                if (row.get("supplier_name").equals(supplierName)) {
                    checkSupplierMainDataResponseDto.setIsInMainData(1);
                    checkSupplierMainDataResponseDto.setOrganizingCode(row.get("organizing_code").toString());
                }
            });
            checkSupplierMainDataResponseDtoList.add(checkSupplierMainDataResponseDto);
        });
        return checkSupplierMainDataResponseDtoList;
    }

    public List<Map<String, Object>> export(LoadDataParams options) {
        if (options.getPageIndex() == -1) {
            options.setPageIndex(0);
            // 因为数芯最多就支持2000，所以没必要更多了
            options.setPageSize(2000);
        }
        return (List<Map<String, Object>>) loadData(options).getData();
    }

    public Map<String, Object> getSupplierContactMobile(String id) {
        GetSupplierContactRequestDto dto = new GetSupplierContactRequestDto();
        dto.setPageNum(1);
        dto.setPageSize(10);
        dto.setId(id);
        SqlApiResponseDto res = getSupplierDataService.getSupplierContact(dto);
        if (res.getData() == null || res.getData().getRows().size() == 0) {
            throw new BusinessLogicException("未找到相关联系人数据");
        }

        Map<String, Object> result = new HashMap<>();
        AtomicReference<Map<String, Object>> finalResult = new AtomicReference<>(result);
        res.getData().getRows().forEach(p -> {
            if (p.get("contact_create_time") != null)
                p.put("contact_create_time", p.get("contact_create_time").toString().substring(0, 10));

            //查看手机号明文
            if (p.get("contact_phone") != null && !p.get("contact_phone").equals("")) {
                //获取查看次数
                String mobile = p.get("contact_phone").toString();
                provinceRadarService.viewTelNumber(mobile);
                //更新查看次数
                Set<String> mobileSet = new HashSet<>();
                mobileSet.add(mobile);
                Map<String, OpTelViewHistory> getTelViewHistories = provinceRadarService.getTelViewHistories(mobileSet);
                if (getTelViewHistories.size() > 0) {
                    p.put("phone_view_times", getTelViewHistories.get(mobile).getViewTimes());
                } else {
                    p.put("phone_view_times", 0);
                }


            }

            finalResult.set(p);
        });

        return finalResult.get();
    }

    public boolean checkSupplierMember(String companyName) throws Exception {
        if (companyName == null || companyName.isEmpty()) {
            return false;
        }
        MpapiClientService remoteService = mpapiClientFactoryService.getMpapiClientService();
        CheckYcgMemberResponseDto responseDto = remoteService.checkYcgMemberRequest(companyName);
        if (responseDto == null) {
            return false;
        }

        return responseDto.getData().get("is_member");
    }
}
